<?php
/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-12 15:43:11 +0200 (Sat, 12 Jul 2008) $
 * $Rev: 1291 $
 * $Author: gavinspearhead $
 * $Id: ajax_admincommands.php 1291 2008-07-12 13:43:11Z gavinspearhead $
 */
define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);

$pathqd = realpath(dirname(__FILE__));

require_once "$pathqd/../functions/ajax_includes.php";
require_once "$pathqd/../functions/pref_functions.php";
require_once "$pathqd/../functions/parse_nfo.php";


function check_extset_link_exists(DatabaseConnection $db, $setID, $type)
{
	$search_type = $db->get_pattern_search_command('REGEXP');
	$sql = " * FROM extsetdata WHERE \"setID\" = '$setID' AND \"type\"='$type' AND \"name\" = 'link' AND \"value\" $search_type '^https?://'";
	$res = $db->select_query($sql);
	return $res !== FALSE;
}


$subject = '';
// Process commands:
if (isset($_REQUEST['type']) && isset($_REQUEST['subject'])) {
	$prefs = load_prefs_clean($db, $userID);
	$type = $_REQUEST['type'];
	$srctype = $_REQUEST['srctype'];
	$subject = $_REQUEST['subject'];

	assert (in_array($type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)));

	$items = array();
	switch ($srctype) {
	case 'setshowesi': // Display extsetinfo
		display_extsetinfo($db, $subject, $type);
		break;
	case 'seteditesi': // Display the edit screen for extsetinfo
		edit_extsetinfo($db, $subject, $type);
		break;
	case 'setsavebintype': // Update the binary type
		save_extsetinfo($db, $subject, $userID, $_REQUEST['values'], $type);
		// No output.
		break;
	case 'setsaveesi': // Save the extsetinfo stuff
		$has_link = check_extset_link_exists($db, $subject, $type);
		$newname = save_extsetinfo($db, $subject, $userID, $_REQUEST['values'], $type);
		if (isset($_REQUEST['values']['link']) && !$has_link && ($_REQUEST['values']['link'] != '')) {
			$file_nfo['link'] = $_REQUEST['values']['link'];
			$file_nfo['binarytype'] = $_REQUEST['binarytype'];
			get_link_info(&$file_nfo);
			$newname = save_extsetinfo($db, $subject, $userID, $file_nfo, $type);
		}
		// Returning the new setname so the browse page can be updated on the fly
		// Actually not really returning but using smarty for name-post-processing (such as icons):
//echo htmlentities ($newname);
		$smarty->assign('maxstrlen', $prefs['maxsetname']);
		$smarty->assign('newname', utf8_decode($newname));
		$smarty->display('formatsetname.tpl');
		break;
	case 'setguessesisafe': // Guess extsetinfo stuff (safe: User needs to approve before we send it to urdland)
		guess_extsetinfo_safe($db,$subject, $type, $userID);
		break;
	case 'setbasketguessesi': // Guess extsetinfo stuff for everything in the basket (not safe, assume that our analysis is flawless)
		basketguess_extsetinfo($db,$subject, $type, $userID);
		break;
	case 'setguessesi': // Guess extsetinfo stuff (not safe, assume that our analysis is flawless)
//echo htmlentities(guess_extsetinfo($db,$subject, $type, $userID));
		$newname = guess_extsetinfo($db,$subject, $type, $userID);
		$smarty->assign('maxstrlen', $prefs['maxsetname']);
		$smarty->assign('newname', $newname);
		$smarty->display('formatsetname.tpl');
		break;
	default:
		die('WHAT?!');
		break;
	}
} else {
	die('Invalid request.');
}

die();
// Functions follow:
function display_extsetinfo(DatabaseConnection $db, $setID, $type)
{
    global $smarty, $LN;
    assert (in_array($type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)));
    // First the extended info:
    $sql = "* FROM extsetdata WHERE \"setID\" = '$setID' AND \"type\" = '$type'";
    $res = $db->select_query($sql);
    // Store it in an easy to use array:
    $extsetinfo = array();
    $extsetinfo['binarytype'] = 0;

    if (is_array($res)) {
        foreach ($res as $row)
            $extsetinfo[$row['name']] = $row['value'];
    }
    $binarytypes = get_binary_types();

    // files by default:
    if ($type == USERSETTYPE_GROUP) {
        $sql = "* FROM setdata WHERE \"ID\" = '$setID'";
        $res = $db->select_query($sql, 1);
        if ($res === FALSE)
            die('could not find set '.$setID);
        $res = $res[0]; // Only 1 row should be returned.

        $groupID = $res['groupID'];
        $size = $res['size'];
        $nicesize = readable_size($size, 1, $LN['byte_short']);
        $articlesmax = $res['articlesmax'];
        $binaries = $res['binaries'];
        $setname = $res['subject'];
    } else {
        $sql = "\"size\", \"rss_id\", \"setname\" FROM rss_sets WHERE \"setid\" = '$setID'";
        $res = $db->select_query($sql, 1);
        if ($res === FALSE)
            die('could not find set '.$setID);
        $size = $res[0]['size'];
        $nicesize = readable_size($size, 1, $LN['byte_short']);
        $groupID = $res[0]['rss_id'];
        $setname = $res[0]['setname'];
        $binaries = 0;
        $articlesmax = 0;
    }
    if (!isset($extsetinfo['name'])) {
        // filter common spam in subjects
        $setname = preg_replace('/(\byEnc\b)|(\breq:)|(\bwww\.[\w\.]*\b)|(\bhttp:\/\/[\w\.]*\b)|([=><#])/i', '', $setname);
        $extsetinfo['name'] = $setname;
    }

    $display = generate_set_info($extsetinfo);

    $smarty->assign('srctype',              'display');         // Edit or just Display?
    $smarty->assign('type',              	$type);         // the type RSS or Groups
    $smarty->assign('setID',                $setID);        // FYI
    $smarty->assign('binarytype',           $extsetinfo['binarytype']); // Binarytype
    $smarty->assign('binarytypes',          $binarytypes);  // All
    $smarty->assign('display',              $display);      // All values

    if ($type == USERSETTYPE_GROUP) {
        $groupname = group_name($db, $groupID);
        $sql = "* FROM binaries_{$groupID} WHERE \"setID\" = '$setID' ORDER BY \"subject\" ASC";
        $res = $db->select_query($sql);
        if ($res === FALSE)
            die('Could not find binaries');
    } else {
        $groupname = feed_name($db, $groupID);
    }

    $rars = $par2s = 0;

    $posters = $files = array();

    if ($type == USERSETTYPE_GROUP) {
        $totalsize = 0;
        foreach ($res as $arr) {
            $file = array();

            $posters[ $arr['fromname'] ] = 1;
            $size = $arr['bytes'];
            $totalsize += $size;
            $size = readable_size($size, 1, $LN['byte_short']);
            $filename = $arr['subject'];
            $filename = str_ireplace('yEnc','',$filename);

            $file['cleanfilename'] = $filename;
            $file['binaryID'] = $arr['binaryID'];
            $file['size'] = $size;
            if (strstr($filename, '.nfo') !== FALSE) // ensure .nfo files are always on top of the list
                array_unshift($files, $file);
            else
                $files[] = $file;

            $arr['subject'] = strtolower($arr['subject']);
            if (strpos($arr['subject'],'.par2') !== FALSE)
                $par2s++;
        }
    } else {
        // now what
        $totalsize = $size;
        $par2s = '';
    }

    $fromnames = '';
    foreach ($posters as $poster => $one)
        $fromnames .= $poster . ", \n";
    $fromnames = rtrim ($fromnames, ",\n ");

    $totalsize = readable_size($totalsize, 1, $LN['byte_short']);

    $smarty->assign('articlesmax',          $articlesmax);
    $smarty->assign('binaries',             $binaries);
    $smarty->assign('type',                 $type);         
    $smarty->assign('groupID',              $groupID);
    $smarty->assign('groupname',            $groupname);
    $smarty->assign('files',                $files);
    $smarty->assign('setname', 		$setname);
    $smarty->assign('fromnames',            $fromnames);
    $smarty->assign('totalsize',            $totalsize);
    $smarty->assign('par2s',                $par2s);
    $smarty->display('ajax_showextsetinfo.tpl');
}


function edit_extsetinfo(DatabaseConnection $db, $setID, $type)
{
	global $smarty;
	assert (in_array($type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)));
	// Get the default name: set subject
	if ($type == USERSETTYPE_GROUP){
		$sql = "\"subject\" FROM setdata WHERE \"ID\" = '$setID'";
		$index = 'subject';
	} else if ($type == USERSETTYPE_RSS) {
		$sql ="\"setname\" FROM rss_sets WHERE \"setid\" = '$setID'";
		$index = 'setname';
	}
	$res = $db->select_query($sql);
	if (!is_array($res))
		die('Set could not be found');
	$setname = $res[0][$index];

	$sql = "* FROM extsetdata WHERE \"setID\" = '$setID' AND \"type\"='$type'";
	$res = $db->select_query($sql);
	// Store it in an easy to use array:
	$extsetinfo = array();
	// Set default values:
	$extsetinfo['binarytype'] = 0;
	$extsetinfo['name'] = $setname;

	// Overwrite default values with stuff from db:
	if (is_array($res))
		foreach ($res as $row)
			$extsetinfo[$row['name']] = ($row['value']);

	$display = generate_set_info($extsetinfo);
	$binarytypes = get_binary_types();

	$smarty->assign('setname',              $setname);        // FYI
	$smarty->assign('setID',                $setID);        // FYI
	$smarty->assign('srctype',              'edit');         // Edit or just Display?
	$smarty->assign('type',                 $type);         //  RSS or group
	$smarty->assign('name',                 $extsetinfo['name']); // Name
	$smarty->assign('binarytype',           $extsetinfo['binarytype']); // Binarytype
	$smarty->assign('binarytypes',          $binarytypes);  // All
	$smarty->assign('display',              $display);      // All values
	$smarty->display('ajax_showextsetinfo.tpl');
}


function guess_extsetinfo_safe(DatabaseConnection $db, $setID, $origin_type, $userID)
{
	assert (in_array($origin_type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)) && is_numeric($userID));
	if (!is_seteditor($db, $userID))
		die('You have no permission to do this!');

	$save = array();

	// Get info (original set name and group name) for this setID:
	list($originalsetname, $groupname) = get_set_info($db, $setID, $origin_type);
	// Guess the binarytype, this returns an array of the binarytype, score, and an array of matching keywords
	list($bintype,$score, $match) = guess_set_type($db, $setID, $groupname, $originalsetname);

	// This is the setname given by the user:
	$newsetname = isset($_REQUEST['setname']) ? $_REQUEST['setname'] : '';
	guess_more_data($score, $bintype, $newsetname, $groupname, $match, $save); 

	// Should now save the values that we could find. They shouldn't be sent to urdland, as it
	// could be totally wrong. Even if the user changes the binarytype and puts in the correct
	// values, the old ones would still exist if they didn't apply to the new binarytype.
	// We can't expect the user to clear the wrong data before switching to the right bintype.
    // So we save them with the 'do not commit' flag and when the user applies, they get changed to 'commit'.
	store_ext_setdata($db, $setID, $save, $origin_type, ESI_COMMITTED);
	// We only save when there wasn't an existing value.. we're just guessing and if someone entered something, it's probably better.
}


function guess_extsetinfo(DatabaseConnection $db, $setID, $origin_type, $userID)
{
	assert (in_array($origin_type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)) && is_numeric($userID));
	if (!is_seteditor($db, $userID))
		die('You have no permission to do this!');

	$save = array();

	// Get info (original set name and group name) for this setID:
	list($originalsetname, $groupname) = get_set_info($db, $setID, $origin_type);
	// Guess the binarytype, this returns an array of the binarytype, score, and an array of matching keywords
	list($bintype,$score, $match) = guess_set_type($db, $setID, $groupname, $originalsetname);

	// This is the setname given by the user:
	$newsetname = isset($_REQUEST['setname']) ? $_REQUEST['setname'] : '';
	guess_more_data($score, $bintype, $newsetname, $groupname, $match, $save); 

	// Should now save the values that we could find. They will be sent to urdland,
	// we are assuming that these values are correct. The user should make sure of it but on
	// a corrective basis instead of preventive.
	$newcompletesetname = store_ext_setdata($db, $setID, $save, $origin_type, ESI_NOT_COMMITTED);
	// We only save when there wasn't an existing value.. we're just guessing and if someone entered something, it's probably better.

	return $newcompletesetname;
}


function basketguess_extsetinfo(DatabaseConnection $db, $setID, $origin_type, $userID)
{
	assert (in_array($origin_type, array(USERSETTYPE_GROUP, USERSETTYPE_RSS)) && is_numeric($userID));
	if (!is_seteditor($db, $userID))
		die('You have no permission to do this!');

	// setID is irrelevant, we do everything in the basket.
	// origin_type is irrelevant, depends on the thing in the basket.

	$save = array();

	// We should have stuff in the basket, just a check:
	if (!isset($_SESSION['setdata']) OR !is_array($_SESSION['setdata']))
		die('No stuff in the friggin basket!');

	foreach ($_SESSION['setdata'] as $set) {
                $setID = $set['setid'];
		$origin_type = USERSETTYPE_GROUP; 
		if ($set['type'] == 'rss') 
			$origin_type = USERSETTYPE_RSS;

		// Get info (original set name and group name) for this setID:
		list($originalsetname, $groupname) = get_set_info($db, $setID, $origin_type);
		// Guess the binarytype, this returns an array of the binarytype, score, and an array of matching keywords
		list($bintype,$score, $match) = guess_set_type($db, $setID, $groupname, $originalsetname);

		// This is the setname given by the user:
		$newsetname = isset($_REQUEST['setname']) ? $_REQUEST['setname'] : '';
		guess_more_data($score, $bintype, $newsetname, $groupname, $match, $save); 

		// Should now save the values that we could find. They will be sent to urdland,
		// we are assuming that these values are correct. The user should make sure of it but on
		// a corrective basis instead of preventive.
		store_ext_setdata($db, $setID, $save, $origin_type, ESI_NOT_COMMITTED);
		// We only save when there wasn't an existing value.. we're just guessing and if someone entered something, it's probably better.
	}
}


?>
